<?php


namespace app\backend\controller\v1;

use app\backend\validate\DegreeValidate;
use app\common\model\Degree as DegreeModel;
use think\exception\ValidateException;

class Degree extends BaseController
{
    /**
     * 程度管理
     *
     * @return \think\Response
     */
    public function index()
    {
        // 程度表
        $user = new DegreeModel();
        // where条件
        $where = input('title');
        // 分页、排序等
        $list = $user->order('id','asc')
            ->field('*')
            ->where(function ($query)use ($where){
            $query->where('title','like','%'.$where.'%');
        })->paginate(10);
        $page = $list->render();
        //获取列表
        return sucessMsg(200, '获取成功！', ['list' => $list, 'total' => count($list),'page'=>$page]);
    }

    /**
     * 添加
     *
     * @return \think\Response
     */
    public function create()
    {
        $user = new DegreeModel();
        $data = input();
        try {
            validate(DegreeValidate::class)->scene('create')->check($data);
            if ($user->save($data)) {
                return sucessMsg(200, '创建成功！');
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择数据id！');
        }
        $data = input();
        try {
            validate(DegreeValidate::class)->scene('update')->check($data);
            if (DegreeModel::update($data, ['id'=>$id])) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(400, '请选择要删除数据的id！');
        }
        $data = DegreeModel::find($id);
        if (empty($data)){
            return errMsg(400, '要删除的数据为空！');
        }
        if (DegreeModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }
}